"""
    Copyright (C) 2009  Andrew Stanton

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

"""
import sys
from inspect import isclass
import re

class Filter(object):
    _filters = {}
    def __new__(cls, **kwargs):
        filter, arg = kwargs.items()[0]
        return cls._filters[filter.capitalize()](arg)

class RegisterFilter(type):
    def __init__(cls, name, bases, attrs):
        Filter._filters[name] = cls
        super(RegisterFilter, cls).__init__(name, bases, attrs)

class FilterObj(object):
    __metaclass__ = RegisterFilter

def _Iter(method, xpath):
    def call(root):
        return (method(i) for i in root.xpath(xpath))
    return call

def Iter(func):
    func.__funcType__ = _Iter
    return func

class Regex(FilterObj):
    def __init__(self, regex):
        assert(isinstance(regex, basestring))
        self.regex = re.compile(regex)

    def __call__(self, function):
        def _regex(method, xpath):
            def call(root):
                nodes = root.xpath(xpath)
                if len(nodes) > 1:
                    return [method(n) for n in nodes if self.regex.search(n)]
                if self.regex.search(nodes): 
                    return method(nodes)
            return call
        function.__funcType__ = _regex
        return function

class Func(FilterObj):
    def __init__(self, func):
        self.wrapper = func

    def __call__(self, function):
        def _func(method, xpath):
            def call(root):
                nodes = root.xpath(xpath)
                if len(nodes) > 1:
                    return [method(n) for n in nodes if self.wrapper(n)]
                if self.wrapper(nodes): 
                    return method(nodes)
            return call
        function.__funcType__ = _func
        return function

class Pattern(FilterObj):
    
    def __init__(self, pattern):
        self.pattern = pattern

    def __call__(self, func):
        try:
            pattern = self.pattern.__iter__()
        except:
            raise TypeError('\'%s\' is not iterable' % type(self.pattern))
        def _Pattern(method, xpath):
            def call(root):
                try:
                    match = pattern.next()
                except StopIteration:
                    return []
                lst = []
                for index, node in enumerate(root.xpath(xpath), 1):
                    if index != match:
                        continue
                    lst.append(method(node))
                    try:
                        match = pattern.next()
                    except StopIteration:
                        return lst
                return lst
            return call
        func.__funcType__ = _Pattern
        return func


